//
//  SourceEditorCommand.m
//  xpel
//
//  Created by wangyankun on 2024/10/24.
//

#import "SourceEditorCommand.h"

@implementation SourceEditorCommand

NSInteger countLeadingSpaces(NSString *string) {
    NSInteger spaceCount = 0;
    NSUInteger length = [string length];

    // 遍历字符串的每个字符，直到遇到非空格字符
    for (NSUInteger i = 0; i < length; i++) {
        unichar character = [string characterAtIndex:i];
        if (character == ' ') {
            spaceCount++;
        } else {
            break; // 遇到非空格字符时停止
        }
    }
    return spaceCount;
}


- (void)performCommandWithInvocation:(XCSourceEditorCommandInvocation *)invocation completionHandler:(void (^)(NSError * _Nullable nilOrError))completionHandler
{
    // Implement your command here, invoking the completion handler when done. Pass it nil on success, and an NSError on failure.
    
    
    NSString *command = invocation.commandIdentifier; // info.plist中定义的 XCSourceEditorCommandIdentifier
    XCSourceTextBuffer *buffer = invocation.buffer;
    XCSourceTextRange *selection = invocation.buffer.selections.firstObject;

    NSInteger lineIndex = selection.start.line; // 行号
    NSString *currentLine = buffer.lines[lineIndex];
    NSInteger tab = countLeadingSpaces(currentLine);
    
    NSMutableString* holder = [NSMutableString new];
    for (int i = 0; i < tab; i++) {
        [holder appendString:@" "];
    }
    
    // com.oel.etcdo.xpel.DelLine
    if ([command containsString:@"DelLine"]) {
        // 删除此行为空格字符串
        buffer.lines[lineIndex] = holder;
        
        // 更新光标位置
        XCSourceTextPosition newPosition = {
            .line = lineIndex,
            .column = holder.length
        };
        selection.start = newPosition;
        selection.end = newPosition;
    }
    
    if ([command containsString:@"NewLine"]) {
        // 新增一行
        [buffer.lines insertObject:holder atIndex:lineIndex+1];

        // 更新光标位置到新行
        XCSourceTextPosition newPosition = {
            .line = lineIndex + 1,
            .column = holder.length
        };
        selection.start = newPosition;
        selection.end = newPosition;
    }
    
    if ([command containsString:@"CopyLine"]) {
        // 复制此行
        [buffer.lines insertObject:currentLine atIndex:lineIndex+1];
        
        // 更新光标位置到新行
        XCSourceTextPosition newPosition = {
            .line = lineIndex + 1,
            .column = selection.start.column
        };
        selection.start = newPosition;
        selection.end = newPosition;
    }
    
    completionHandler(nil);
      
}

@end

